package com.xunua.networkproject.Retrofit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.xunua.networkproject.R;
import com.xunua.networkproject.RetrofitBean.CommentBean;
import com.xunua.networkproject.RetrofitBean.CommentResultBean;
import com.xunua.networkproject.RetrofitBean.PostFileResultBean;
import com.xunua.networkproject.Utils.FileUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static java.net.HttpURLConnection.HTTP_OK;

public class RetrofitActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
    }

    public void get(View view) {
        RetrofitServiceImp.getText().enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Toast.makeText(RetrofitActivity.this, "get:"+response.body(), Toast.LENGTH_SHORT).show();
                Log.e("TAG", "onResponse: "+Thread.currentThread().getName() );
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Toast.makeText(RetrofitActivity.this, "get请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void getMore(View view) {
        RetrofitServiceImp.getParam("等等我，马上到！", "520", 0).enqueue(new Callback<RetrofitServiceImp.ParamBean>() {
            @Override
            public void onResponse(Call<RetrofitServiceImp.ParamBean> call, Response<RetrofitServiceImp.ParamBean> response) {
                Toast.makeText(RetrofitActivity.this, "我来了："+response.body().getData().getKeyword(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<RetrofitServiceImp.ParamBean> call, Throwable t) {
                Toast.makeText(RetrofitActivity.this, "getMore请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void getMoreMap(View view) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("keyword","你好 queryMap");
        map.put("page","10");
        map.put("order",1);
        RetrofitServiceImp.getParam(map).enqueue(new Callback<RetrofitServiceImp.ParamBean>() {
            @Override
            public void onResponse(Call<RetrofitServiceImp.ParamBean> call, Response<RetrofitServiceImp.ParamBean> response) {
                Toast.makeText(RetrofitActivity.this, "我又又又来了："+response.body().getData().getKeyword(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<RetrofitServiceImp.ParamBean> call, Throwable t) {
                Toast.makeText(RetrofitActivity.this, "getMoreQuery请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void post(View view) {
        Map<String,Object> map = new HashMap();
        map.put("string", "这是我的@query内容！！！");
        RetrofitServiceImp.postString(map).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Toast.makeText(RetrofitActivity.this, "请求成功:"+response.body(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }
    public void postString(View view) {
        String url="/post/string?string=这是我的@URl内容！！！";
        RetrofitServiceImp.postString(url).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Toast.makeText(RetrofitActivity.this, "请求成功:"+response.body(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    public void postBody(View view) {
        CommentBean commentBean = new CommentBean("123", "你的文章写的太好了！赞！");
        Call<CommentResultBean> call = RetrofitServiceImp.postComment(commentBean);
        call.enqueue(new Callback<CommentResultBean>() {
            @Override
            public void onResponse(Call<CommentResultBean> call, Response<CommentResultBean> response) {
                Toast.makeText(RetrofitActivity.this, "成功"+response.body(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<CommentResultBean> call, Throwable t) {
                Toast.makeText(RetrofitActivity.this, "失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private final int REQUEST_CODE_CHOOSE=1;
    public void postFile(View view) {
        Matisse.from(this)
                .choose(MimeType.ofAll())
                .countable(true)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .showPreview(false) // Default is `true`
                .theme(R.style.Matisse_Dracula)//R.style.Matisse_Zhihu (light mode)      R.style.Matisse_Dracula (dark mode)
                .forResult(REQUEST_CODE_CHOOSE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {//上传单个文件
            List<Uri> mSelected;
            mSelected = Matisse.obtainResult(data);
            Uri uri = mSelected.get(0);
            String path = FileUtils.getPath(this, uri);
            String filename = new File(path).getName();
            try (InputStream inputStream = getContentResolver().openInputStream(uri)) {
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                int len;
                byte[] buf = new byte[1024 * 4];
                while ((len = inputStream.read(buf)) != -1) {
                    output.write(buf, 0, len);
                }
                output.flush();
                byte[] bytes = output.toByteArray();
                RequestBody requestBody = RequestBody.create(bytes,MediaType.parse(getContentResolver().getType(uri)));
                MultipartBody.Part part = MultipartBody.Part.createFormData("file", filename, requestBody);
                Call<PostFileResultBean> call = RetrofitServiceImp.postFile(part,"@Header 123123123");
                output.close();
                call.enqueue(new Callback<PostFileResultBean>() {
                    @Override
                    public void onResponse(Call<PostFileResultBean> call, Response<PostFileResultBean> response) {
                        Toast.makeText(RetrofitActivity.this, "上传单个文件成功!" + response.toString(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(Call<PostFileResultBean> call, Throwable t) {
                        Toast.makeText(RetrofitActivity.this, "上传单个文件失败!", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (requestCode == REQUEST_CODE_CHOOSE_MORE && resultCode == RESULT_OK) {//上传多个文件
            List<Uri> mSelected;
            mSelected = Matisse.obtainResult(data);
            List<MultipartBody.Part> parts = new ArrayList<>();
            ByteArrayOutputStream output=null;
            for (Uri uri :
                    mSelected) {
                String path = FileUtils.getPath(this, uri);
                String filename = new File(path).getName();
                try (InputStream inputStream = getContentResolver().openInputStream(uri)) {
                    output = new ByteArrayOutputStream();
                    int len;
                    byte[] buf = new byte[1024 * 4];
                    while ((len = inputStream.read(buf)) != -1) {
                        output.write(buf, 0, len);
                    }
                    output.flush();
                    byte[] bytes = output.toByteArray();
                    RequestBody requestBody = RequestBody.create(bytes,MediaType.parse(getContentResolver().getType(uri)));
                    MultipartBody.Part part = MultipartBody.Part.createFormData("files", filename, requestBody);
                    parts.add(part);
                }catch (Exception e){

                }finally {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            RetrofitServiceImp.postFiles(parts).enqueue(new Callback<PostFileResultBean>() {
                @Override
                public void onResponse(Call<PostFileResultBean> call, Response<PostFileResultBean> response) {
                    Toast.makeText(RetrofitActivity.this, "成功"+response.body(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(Call<PostFileResultBean> call, Throwable t) {
                    Toast.makeText(RetrofitActivity.this, "失败", Toast.LENGTH_SHORT).show();
                }
            });
        }

        if (requestCode == REQUEST_CODE_CHOOSE_MORE_PARAMS && resultCode == RESULT_OK) {//上传单个个文件并携带参数
            List<Uri> mSelected;
            mSelected = Matisse.obtainResult(data);
            Uri uri = mSelected.get(0);
            String path = FileUtils.getPath(this, uri);
            String filename = new File(path).getName();
            ByteArrayOutputStream output=null;
            try (InputStream inputStream = getContentResolver().openInputStream(uri)) {
                output = new ByteArrayOutputStream();
                int len;
                byte[] buf = new byte[1024 * 4];
                while ((len = inputStream.read(buf)) != -1) {
                    output.write(buf, 0, len);
                }
                output.flush();
                byte[] bytes = output.toByteArray();
                RequestBody requestBody = RequestBody.create(bytes, MediaType.parse(getContentResolver().getType(uri)));
                MultipartBody.Part part = MultipartBody.Part.createFormData("file", filename, requestBody);
                HashMap<String, String> params = new HashMap<>();
                params.put("description","这是我上传的一张图片"+filename);
                params.put("isFree","true");
                RetrofitServiceImp.postFileParams(part,params).enqueue(new Callback<PostFileResultBean>() {
                    @Override
                    public void onResponse(Call<PostFileResultBean> call, Response<PostFileResultBean> response) {
                        if (response.code()==200) {
                            Toast.makeText(RetrofitActivity.this, "上传成功"+response.body().getData(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<PostFileResultBean> call, Throwable t) {
                        Toast.makeText(RetrofitActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }catch (Exception e){

            }finally {
                try {
                    output.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        }
    private final int REQUEST_CODE_CHOOSE_MORE=2;
    public void postFiles(View view) {
        Matisse.from(this)
                .choose(MimeType.ofAll())
                .countable(true)
                .maxSelectable(9)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .showPreview(false) // Default is `true`
                .forResult(REQUEST_CODE_CHOOSE_MORE);
    }

    private final int REQUEST_CODE_CHOOSE_MORE_PARAMS =3;
    public void postFilesParams(View view) {
        Matisse.from(this)
                .choose(MimeType.ofAll())
                .countable(true)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .showPreview(false) // Default is `true`
                .forResult(REQUEST_CODE_CHOOSE_MORE_PARAMS);
    }

    public void postLogin(View view) {
        RetrofitServiceImp.postLogin("xunua","pwd123456").enqueue(new Callback<PostFileResultBean>() {
            @Override
            public void onResponse(Call<PostFileResultBean> call, Response<PostFileResultBean> response) {
                if (response.code()==200)
                Toast.makeText(RetrofitActivity.this, "请求成功"+response.body().getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<PostFileResultBean> call, Throwable t) {
                Toast.makeText(RetrofitActivity.this, "请求成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void download(View view) {
        Handler handler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                Toast.makeText(RetrofitActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
            }
        };
        RetrofitServiceImp.download("/download/1").enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.code() == HTTP_OK) {
                    //取文件名称-header
                    //写文件 但是这里是ui线程不可以写
                    Headers headers = response.headers();
                    for (int i = 0; i < headers.size(); i++) {
                        Log.e("TAG", "onResponse: " + headers.name(i) + "value:" + headers.value(i));
                    }
                    String fileName = headers.get("Content-disposition").replace("attachment; filename=", "");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            InputStream inputStream = response.body().byteStream();
                            ContentResolver contentResolver = getContentResolver();
                            Uri contentUri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
                            ContentValues contentValues = new ContentValues();
                            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME,fileName);
                            contentValues.put(MediaStore.Images.Media.MIME_TYPE,"image/*");
                            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH,"Pictures/Retrofit王者荣耀2.0");
                            Uri insert = contentResolver.insert(contentUri, contentValues);
                            if (insert==null){
                                Log.e("RetrofitActivity", "onResponse: Imginserturi异常" );
                                return;
                            }
                            try (OutputStream outputStream=contentResolver.openOutputStream(insert)){
                                byte[] buf = new byte[1024*4];
                                int length;
                                while ((length=inputStream.read(buf))!=-1){
                                    outputStream.write(buf,0,length);
                                }
                                outputStream.flush();
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }finally {
                                try {
                                    inputStream.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                handler.sendEmptyMessage(0);
                            }
                        }
                    }).start();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }
}
